package com.opdar.platform.core.base;

import com.opdar.platform.utils.Utils;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class RestRouter extends Router {

    private LinkedList<String> matchers = new LinkedList<String>();
    private List<String> mapping = new LinkedList<String>();

    public int getMappingSize() {
        return mapping.size();
    }

    public RestRouter(String name) {
        super(name);

        LinkedList<Integer> indexed = new LinkedList<Integer>();
        indexed.add(0);
        String factor = Utils.parseSignFactor("{{", "}}", "(.*)", name, mapping,indexed);

        for (int i = 0; i < indexed.size(); i+=2) {
            matchers.add(factor.substring(indexed.get(i),indexed.get(i+1)));
        }
    }

    public boolean match(String path,Map<String,Object> _parameters){
        Map<String,Object> parameters = new HashMap<String, Object>();
        String correctRouter = Utils.testRouter(path);
        int valueSize = matchers.size() - 1;
        int lastIndex = -1;
        int parameterCount = 0;
        for (int i = 0; i < matchers.size(); i++) {
            String match = matchers.get(i);
            int index = correctRouter.indexOf(match,lastIndex);
            if(index == -1 ){
                return false;
            }
            if(i == 0 && index > 0){
                return false;
            }
            if(match.trim().equals("") && i == valueSize){
                index = correctRouter.length();
            }

            if(lastIndex >=0){
                String value = correctRouter.substring(lastIndex,index);
                if(value.contains("/")){
                    return false;
                }
                String key = mapping.get(mapping.size() - (valueSize - i) - 1);
                parameterCount++;
                if(_parameters != null && !_parameters.containsKey(key)){
                    parameters.put(key,value);
                }
            }
            lastIndex = index + match.length();
        }
        if(mapping.size() == parameterCount){
            _parameters.putAll(parameters);
            return true;
        }
        return false;
    }

}
